package java_thinking.unit_14._14_2;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description :
 * @author: cww
 * @DateTime: 2019-03-26 23:31
 */
class BaseShape {
    boolean highLighted = false;
    static List<BaseShape> shapes = new ArrayList<>();

    /**
     * 子类创建了对象默认添加到list中
     */
    BaseShape(){
        shapes.add(this);
    }
    public void setHighLighted() {
        highLighted = true;
    }
    public void resetHighLighted() {
        highLighted = false;
    }
    @Override
    public String toString() {
        return getClass().getName() + (highLighted?" highLighted":" normal");
    }
    void draw(){
        System.out.println(this+"draw()");
    }
    public static void setHighLightList(Class<?> type){
        for (BaseShape shape : shapes) {
            if (type.isInstance(shape)){
                shape.setHighLighted();
            }
        }
    }
    public static void resetHighLightList(Class<?> type) {
        for (BaseShape shape : shapes){
            if (type.isInstance(shape)){
                shape.resetHighLighted();
            }
        }
    }

    static void setHighLightByInvoke(Class<?> type, String methodName){
        try {
            //getMethod(方法名,参数类型)
            Method m = BaseShape.class.getMethod(methodName,type.getClass());
            for (BaseShape shape : shapes){
                if (type.isInstance(shape)){
                    m.invoke(shape,type);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            throw new RuntimeException(e);
        }
    }
}
class Circle extends BaseShape {}
class Square extends BaseShape {}
class Triangle extends BaseShape {}

public class E06_1 {
    public static void main(String[] args) {
        List<BaseShape> shapes = Arrays.asList(new Circle(),new Square(),new Triangle(),new Square(),new Triangle(),new Circle());
        BaseShape.setHighLightList(Circle.class);

        BaseShape.setHighLightByInvoke(Square.class,"setHighLightList");
        for (BaseShape shape:shapes){
            shape.draw();
            System.out.println(shape);
            System.out.println("===================");
        }
        BaseShape.setHighLightByInvoke(Circle.class,"resetHighLightList");
        BaseShape.setHighLightByInvoke(Square.class,"resetHighLightList");
        for (BaseShape shape:shapes){
            shape.draw();
            System.out.println(shape);
            System.out.println("===================");
        }
    }
}
